﻿using System;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Activation;
using System.ServiceModel.Syndication;
using System.Collections.Specialized;
using System.Runtime.Serialization;
using System.Collections.Generic;
using EnterpriseServices.DalEf;
using EnterpriseServices.DTO;
using Microsoft.ServiceModel.Web;

namespace EnterpriseServices.Service
{
    /// <summary>
    /// 
    /// </summary>
    //[ServiceBehavior(IncludeExceptionDetailInFaults = true, InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class ValidationServiceREST : ValidationServiceBase, IValidationManagerREST
    {
        #region IValidationManagerREST Members

        /// <summary>
        /// Returns true if the userName exists.
        /// </summary>
        /// <param name="userName">The username.</param>
        /// <returns></returns>
        [TransactionFlow(TransactionFlowOption.NotAllowed)]
        [OperationBehavior(TransactionScopeRequired = false)]
        [WebGet(UriTemplate = "/DoesUserExist/{userName}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
        bool IValidationManagerREST.DoesUserExist(string userName)
        {
            if (String.IsNullOrEmpty(userName))
                throw new FaultException("userName is null or empty.");
            
            try
            {
                return base.DoesUserExist((userName).Replace("-","\\"));
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("EnterpriseServices", ex.Message, System.Diagnostics.EventLogEntryType.Error);
                return false;
            }
        }

        /// <summary>
        /// Returns true if the userName exists.
        /// </summary>
        /// <param name="userName">The username.</param>
        /// <returns></returns>
        [TransactionFlow(TransactionFlowOption.NotAllowed)]
        [OperationBehavior(TransactionScopeRequired = false)]
        [WebGet(UriTemplate = "/DoesUserExistPass/{userName};{password}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
        bool IValidationManagerREST.DoesUserExistPass(string userName, string password)
        {
            if (String.IsNullOrEmpty(userName))
                throw new FaultException("userName is null or empty.");
            if (String.IsNullOrEmpty(password))
                throw new FaultException("password is null or empty.");
            
            try
            {
                return base.DoesUserExistPass(userName.Replace("-", "\\"), password);
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("EnterpriseServices", ex.Message, System.Diagnostics.EventLogEntryType.Error);
                return false;
            }
        }

        /// <summary>
        /// Returns true if a userName belongs to the requested role.
        /// A userName belongs to a role if
        /// <list type="bullet">
        /// 		<item>the userName is directly attached to a role</item>
        /// 		<item>the groups the userName belongs to are attached to a role</item>
        /// 		<item>the groups' child groups are attached to a role</item>
        /// 		<item>the associated groups the userName belongs to are attached to a role</item>
        /// 	</list>
        /// Regarding Groups, a userName only belongs to a role if he is eiher a group owner or a group member.
        /// </summary>
        /// <param name="applicationName">Name of the application.</param>
        /// <param name="roleName">Name of the role.</param>
        /// <param name="userName">Name of the userName.</param>
        /// <returns></returns>
        [TransactionFlow(TransactionFlowOption.Allowed)]
        [OperationBehavior(TransactionScopeRequired = false)]
        [WebGet(UriTemplate = "/IsUserInRole/{applicationName};{roleName};{userName}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
        bool IValidationManagerREST.IsUserInRole(string applicationName, string roleName, string userName)
        {
            if (String.IsNullOrEmpty(applicationName))
                throw new FaultException("applicationName is null or empty.");
            if (String.IsNullOrEmpty(roleName))
                throw new FaultException("roleName is null or empty.");
            if (String.IsNullOrEmpty(userName))
                throw new FaultException("userName is null or empty.");
            
            try
            {
                return base.IsUserInRole(applicationName, 
                                                          roleName,
                                                          userName.Replace("-", "\\"));
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("EnterpriseServices", ex.Message, System.Diagnostics.EventLogEntryType.Error);
                return false;
            }
        }

        /// <summary>
        /// Returns true if a userName belongs to the requested role.
        /// A userName belongs to a role if
        /// <list type="bullet">
        /// 		<item>the userName is directly attached to a role</item>
        /// 		<item>the groups the userName belongs to are attached to a role</item>
        /// 		<item>the groups' child groups are attached to a role</item>
        /// 		<item>the associated groups the userName belongs to are attached to a role</item>
        /// 	</list>
        /// Regarding Groups, a userName only belongs to a role if he is eiher a group owner or a group member.
        /// </summary>
        /// <param name="applicationName">Name of the application.</param>
        /// <param name="roleName">Name of the role.</param>
        /// <param name="userName">Name of the userName.</param>
        /// <returns></returns>
        [TransactionFlow(TransactionFlowOption.Allowed)]
        [OperationBehavior(TransactionScopeRequired = false)]
        [WebGet(UriTemplate = "/IsUserInRolePass/{applicationName};{roleName};{userName};{password}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
        bool IValidationManagerREST.IsUserInRolePass(string applicationName, string roleName, string userName, string password)
        {
            if (String.IsNullOrEmpty(applicationName))
                throw new FaultException("applicationName is null or empty.");
            if (String.IsNullOrEmpty(roleName))
                throw new FaultException("roleName is null or empty.");
            if (String.IsNullOrEmpty(userName))
                throw new FaultException("userName is null or empty.");
            if (String.IsNullOrEmpty(password))
                throw new FaultException("password is null or empty.");
            
            try
            {
                return base.IsUserInRolePass(applicationName, roleName, userName.Replace("-", "\\"), password);
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("EnterpriseServices", ex.Message, System.Diagnostics.EventLogEntryType.Error);
                return false;
            }
        }

        /// <summary>
        /// Determines whether [is group in role] [the specified application name].
        /// </summary>
        /// <param name="applicationName">Name of the application.</param>
        /// <param name="roleName">Name of the role.</param>
        /// <param name="groupName">Name of the group.</param>
        /// <returns>
        /// 	<c>true</c> if [is group in role] [the specified application name]; otherwise, <c>false</c>.
        /// </returns>
        [TransactionFlow(TransactionFlowOption.Allowed)]
        [OperationBehavior(TransactionScopeRequired = false)]
        [WebGet(UriTemplate = "/IsGroupInRole/{applicationName};{roleName};{groupName}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
        bool IValidationManagerREST.IsGroupInRole(string applicationName, string roleName, string groupName)
        {
            if (String.IsNullOrEmpty(applicationName))
                throw new FaultException("applicationName is null or empty.");
            if (String.IsNullOrEmpty(roleName))
                throw new FaultException("roleName is null or empty.");
            if (String.IsNullOrEmpty(groupName))
                throw new FaultException("groupName is null or empty.");
            try
            {
                return base.IsGroupInRole(applicationName, roleName, groupName);
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("EnterpriseServices", ex.Message, System.Diagnostics.EventLogEntryType.Error);
                return false;
            }
        }

         /// <summary>
        /// Gets the name of the userNames by application.
        /// </summary>
        /// <param name="applicationName">Name of the application.</param>
        /// <returns></returns>
        [WebHelp(Comment = "Gets the name of the userNames by application")]
        [TransactionFlow(TransactionFlowOption.Allowed)]
        [OperationBehavior(TransactionScopeRequired = false)]
        [WebGet(UriTemplate = "/GetUsersByApplicationName/{applicationName}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
        List<EnterpriseServices.DTO.User> IValidationManagerREST.GetUsersByApplicationName(string applicationName)
        {
            if (String.IsNullOrEmpty(applicationName))
                throw new FaultException("applicationName is null or empty.");

            try
            {
                List<EnterpriseServices.DalEf.User> myUserList = base.GetUsersByApplicationName(applicationName);

                List<EnterpriseServices.DTO.User> myCollection = new List<EnterpriseServices.DTO.User>();
                myUserList.ForEach(ur =>
                {
                    myCollection.Add(new EnterpriseServices.DTO.User(ur.UserName, ur.IsADDeployed)) ;
                });
                return myCollection;
                
                //int myCount = myUserList.Count;
                //int i = 0;
                //String[] myStringList = new String[myCount];

                //myUserList.ForEach(ur =>
                //{
                //    myStringList[i] = ur.UserName.ToString();
                //    i += 1;
                //});
                //return myStringList;
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("EnterpriseServices", ex.Message, System.Diagnostics.EventLogEntryType.Error);
                return null;
            }
        }     

        #endregion
    }
}
